package com.winit.cloudlink.mgmt.recovery;

import com.winit.cloudlink.message.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.common.IOUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

@Slf4j
public class FileMessageReader implements MessageReader {
    @Override
    public void read(File source, MessageReaderHandler messageReaderHandler) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(source));
            String line = null;
            do {
                line = reader.readLine();
                if (isNotBlank(line)) {
                    Message message = MessageHelper.buildMessage(line);
                    messageReaderHandler.process(message);
                }
            } while (line != null);
        } catch (IOException e) {
            log.error("读取文件时发生错误。", e);
        } catch (Exception e) {
            log.error("导入消息时发生错误。", e);
        } finally {
            IOUtils.closeStream(reader);
        }
    }
}
